import { createRouter, createWebHistory } from 'vue-router'
// import emitter from '@/utils/emitter'
import { useScrollStore } from '@/store/scrollStore'
const Main = () => import('../pages/Main/Main.vue')
const Article = () => import('../pages/Article/Article.vue')
const Tag = () => import ('../pages/Tag/Tag.vue') 
const Update = () => import('../pages/Update/Update.vue')
const Friends = () => import('../pages/Friends/Friends.vue')
// console.log(import('../pages/Article/Article.vue')); //是一个promise函数

//在这里使用const scrollStore = useScrollStore()会报错，因为router在pinia之前

const routes = [{
    path: '/',
    component: Main
}, {
    path: '/article',
    name: 'article',
    component: Article
},{
    path:'/tag',
    name:'tag',
    component:Tag
},{
    path:'/update',
    name:'update',
    component:Update
},{
    path:'/friends',
    name:'friends',
    component:Friends
}]


const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior(to,from){    //router的滚动
        console.log(to,from);
        const scrollStore = useScrollStore()
        if(to.fullPath === '/'){        //如果要去的路由为主页
            return {
                top:scrollStore.mainScrollTop,  //回到离开时的高度
                behavior:'smooth'
            }
        }       //去别的地方，直接卷去顶部
        return {
            top:400,
            behavior:'smooth'
        }
    }
})

router.beforeEach((to,from)=>{      //路由守卫
    const {storeMainScroll} = useScrollStore()
    
    if(to.fullPath === '/article'){   //如果要去看文章
        // emitter.emit('readArticle')         //通知开启目录
    }
    
    if(from.fullPath === '/'){  //切换路由时，如果从主页来，则储存浏览进度
        storeMainScroll()
    }
})

export default router